﻿// console.log(new Decimal(0.2).add(new Decimal(0.1)).toString());

/**
 * @typedef {Object} AppData
 * @property {number} EA   上次APP，用的EA值;  初始值 EA_DEFAULT
 * @property {number[]} EA_list  初始值  [EA_DEFAULT, EA_DEFAULT_2]
 * @property {number} EA_min   初始值  MIN_EA_DEFAULT
 * @property {number} EA_max   初始值  MAX_EA_DEFAULT
 * @property {number} set_EA_t 上次修改EA时的时间戳，默认值undefined,到期结束时设置为undefined
 * @property {number} ck_EA_t  上次检查确认EA后的时间戳，默认值undefined
 */

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

/** EA默认值*/
const EA_DEFAULT = 14.359;
const EA_DEFAULT_2 = 15.193;

const DAY_SHIFT_EA_CK_TIME = "08:20:00"; // 白班检查确认EA时间
const NIGHT_SHIFT_EA_CK_TIME = "20:20:00"; // 夜班检查确认EA时间

const MIN_EA_DEFAULT = 1;
const MAX_EA_DEFAULT = 240;

const DATA_KEY = "EA_calc_app_data_key";


const SELECT_STATE = {
  /** @deprecated 未选中的状态 [废弃]*/
  NONE: 0,
  /** 对应选中卷1良品EA数 */
  J1: 1,
  /** 对应选中卷2良品EA数 */
  J2: 2,
  /** 对应选中卷3良品EA数 */
  J3: 3,
  /** 对应选中卷4良品EA数 */
  J4: 4,
};

var globalData = {
  /**@type {AppData} */
  appData: null,

  clickFlag: null,
  clickFlag1: null,
  /** setEATip timeout*/
  timeout: null,

  /**@type {{ i: number, EA: number, act: number,res: number, sel: SELECT_STATE[], }[]} */
  data: [],
  /**J1是否被选中 */
  J1_sel: false,
  /**J2是否被选中 */
  J2_sel: false,
  /**J1是否被选中 */
  J3_sel: false,
  /**J2是否被选中 */
  J4_sel: false,


  keyboard: {
    /**当前输入框值校验结果 */
    iptCheckRes: false,
    /**上一次输入值 */
    lastVal: '',
  }
};

/**主函数 */
function main() {



  /**读取EA值 */
  // localStorage.removeItem(DATA_KEY);
  let res = getCookie(DATA_KEY);
  if (res === null) {
    /**@type {AppData} */
    let data = {
      EA: EA_DEFAULT,
      EA_list: [EA_DEFAULT, EA_DEFAULT_2],
      EA_max: MAX_EA_DEFAULT,
      EA_min: MIN_EA_DEFAULT,
      set_EA_t: undefined,
      ck_EA_t: undefined
    };
    res = JSON.stringify(data);
    // localStorage.setItem(DATA_KEY, res);
    setCookie(DATA_KEY, res, 36500);
    console.log("初始化appData并保存");
  }
  console.log("appData:", res);
  globalData.appData = JSON.parse(res);
  console.log("appData:", globalData.appData);


  // console.log("EA:", EA);

  /**生成select option */
  // let o_ea_sel = document.getElementById("ea_sel");
  let o_ea_show = document.getElementById("ea_show");
  let o_EA_list = document.getElementById("EA_list");

  globalData.appData.EA_list.forEach(function (el) {
    /** 
    let newOption = document.createElement("option");
    newOption.text = el + "";
    newOption.value = el;
    newOption.id = "sel-opt-" + el;
    if (globalData.appData.EA === el) {
      newOption.selected = true;
    }
    o_ea_sel.add(newOption);
    */



    /*
    let o_new = document.createElement("div");
    o_new.classList.add("EA", "mybtn");
    o_new.id = "set-EA-" + el;
    o_new.innerText = el;
    o_new.onclick = function () { setEADoOnClick(el) };
    o_new.ondblclick = function () { setEADoOnDblClick(el) };
    // o_EA_list.append(o_new);
    // o_EA_list.innerHTML = o_EA_list.innerHTML + o_new;
    */

    let o_new_str = '<div class="EA mybtn';


    if (globalData.appData.EA === el) {
      o_ea_show.innerText = el;
      document.getElementById("ea_show_ck").innerText = el;
      // o_new.classList.add("selected");
      o_new_str += " selected";
    }
    // o_new_str += ('" ondblclick="delEADoOnDblClick(event,' + el + ')" onclick="setEADoOnClick(' + el + ')" id="set-EA-' + el + '">' + el + "</div>");
    o_new_str += ('" onclick="setEADoOnClick(' + el + ')" id="set-EA-' + el + '">' + '\n<span>' + el + '</span>\n<div class="del_btn" onclick="delEADoOnDblClick(event,' + el + ')">×</div>');

    o_EA_list.innerHTML += o_new_str;

  });

  document.getElementById("EA_min").value = globalData.appData.EA_min;
  document.getElementById("EA_max").value = globalData.appData.EA_max;


  createAllEANumsByEA();

  // console.log(globalData.data);

  setEATipShow();

  ckEATimeoutWork();


  // 给输入键盘弹框 绑定 鼠标拖拽功能

}



// main();
/**
 * 需要获取页面元素，延时100ms执行主函数
 */
setTimeout(function () {
  // console.log("...");
  main();
}, 100);

/**
 * 当总长值被修改后；头部显示提示文字。
 * 1天内红色，2-3天灰色
 */
function setEATipShow() {
  document.getElementById("ea_cg_tip").classList.remove("gone");
  document.getElementById("ea_cg_tip").innerText = "";
  if (globalData.appData.set_EA_t !== undefined) {
    let o_tip = document.getElementById("ea_cg_tip");
    let t_set = globalData.appData.set_EA_t;
    o_tip.innerText = "当前总长值已修改!!!" + new Date(t_set).toLocaleString();
    let now = Date.now();
    let delta = (now - t_set);

    if (globalData.timeout !== null || globalData.timeout) {
      clearTimeout(globalData.timeout);
    }
    if (delta <= 1 * 86400000) {
      // 1天内红色高亮
      globalData.timeout = setTimeout(function () {
        document.getElementById("ea_cg_tip").classList.add("gone");
        clearTimeout(globalData.timeout);
        globalData.timeout = setTimeout(function () {
          document.getElementById("ea_cg_tip").innerText = "";
          document.getElementById("ea_cg_tip").classList.remove("gone");
          globalData.appData.set_EA_t = undefined;
          // localStorage.setItem(DATA_KEY, JSON.stringify(globalData.appData));
          setCookie(DATA_KEY, JSON.stringify(globalData.appData), 36500);
          clearTimeout(globalData.timeout);
        }, 2 * 86400000);
        //}, 5000);
      }, 1 * 86400000 - delta);
      //}, 5000);
    } else if (delta <= 3 * 86400000) {
      // 2-3天灰
      o_tip.classList.add("gone");
      globalData.timeout = setTimeout(function () {
        document.getElementById("ea_cg_tip").innerText = "";
        document.getElementById("ea_cg_tip").classList.remove("gone");
        globalData.appData.set_EA_t = undefined;
        // localStorage.setItem(DATA_KEY, JSON.stringify(globalData.appData));
        setCookie(DATA_KEY, JSON.stringify(globalData.appData), 36500);
        clearTimeout(globalData.timeout);
      }, 3 * 86400000 - delta);
    } else {
      o_tip.innerText = "";
      o_tip.classList.remove("gone");
      globalData.appData.set_EA_t = undefined;
      // localStorage.setItem(DATA_KEY, JSON.stringify(globalData.appData));
      setCookie(DATA_KEY, JSON.stringify(globalData.appData), 36500);
    }
  }
}


/**
 * 单击事件
 * @param {*} EA 
 * @param {*} res 
 */
function doOnClick(EA, res, index) {
  // xxxx
  // console.log(EA, res, index);
  /**只考虑一次只能点一个地方 */
  const wait = 100;
  let now = Date.now();
  if (globalData.clickFlag) {
    // 取消上次延时未执行的方法
    globalData.clickFlag = clearTimeout(globalData.clickFlag);

  }
  globalData.clickFlag = setTimeout(function () {
    /**单击事件处理 */
    console.log("单击", EA, res, index);

    let item = globalData.data[index];
    // 判断能不能选
    // if (item.sel != SELECT_STATE.NONE) {
    //   return;
    // } else {
    if (!globalData.J1_sel) {
      item.sel.push(SELECT_STATE.J1);
      globalData.J1_sel = true;


      document.getElementById("J1_EA").value = item.EA;
      document.getElementById("J1_act").value = item.act;
      document.getElementById("J1_res").value = item.res;

      document.getElementById('num-' + index).classList.add("selected");

      document.getElementById('order-' + index + '-1').classList.add("selected");

      calc();

    } else if (!globalData.J2_sel) {
      item.sel.push(SELECT_STATE.J2);
      globalData.J2_sel = true;

      document.getElementById("J2_EA").value = item.EA;
      document.getElementById("J2_act").value = item.act;
      document.getElementById("J2_res").value = item.res;

      document.getElementById('num-' + index).classList.add("selected");
      document.getElementById('order-' + index + '-2').classList.add("selected");

      calc();
    } else if (!globalData.J3_sel) {
      item.sel.push(SELECT_STATE.J3);
      globalData.J3_sel = true;

      document.getElementById("J3_EA").value = item.EA;
      document.getElementById("J3_act").value = item.act;
      document.getElementById("J3_res").value = item.res;

      document.getElementById('num-' + index).classList.add("selected");
      document.getElementById('order-' + index + '-3').classList.add("selected");

      calc();
    } else if (!globalData.J4_sel) {
      item.sel.push(SELECT_STATE.J4);
      globalData.J4_sel = true;

      document.getElementById("J4_EA").value = item.EA;
      document.getElementById("J4_act").value = item.act;
      document.getElementById("J4_res").value = item.res;

      document.getElementById('num-' + index).classList.add("selected");
      document.getElementById('order-' + index + '-4').classList.add("selected");

      calc();
    }
    // }

  }, wait);
}


function ckEATimeoutWork() {
  const ck_t = globalData.appData.ck_EA_t;
  // 确认本班次是否检查过
  if (ck_t !== undefined) {
    let now = Date.now();
    // 当天白班开始前时间
    let day_s_ck_t = new Date(((new Date()).getYear() + 1900) + '/' + ((new Date()).getMonth() + 1) + '/' + (new Date()).getDate() + ' ' + DAY_SHIFT_EA_CK_TIME);
    // 明天白班开始前时间
    let day_s_ck_t_n = day_s_ck_t.getTime() + 86400000;
    day_s_ck_t = day_s_ck_t.getTime();
    // 当天夜班开始前时间
    let night_s_ck_t = new Date(((new Date()).getYear() + 1900) + '/' + ((new Date()).getMonth() + 1) + '/' + (new Date()).getDate() + ' ' + NIGHT_SHIFT_EA_CK_TIME);
    // 昨天夜班开始前时间
    let night_s_ck_t_p = night_s_ck_t.getTime() - 86400000;
    night_s_ck_t = night_s_ck_t.getTime();
    // console.log(new Date());
    // console.log(day_s_ck_t.getTime(),night_s_ck_t.getTime());
    // console.log(night_s_ck_t_p, day_s_ck_t, night_s_ck_t, day_s_ck_t_n);
    if (now >= night_s_ck_t_p && now <= day_s_ck_t) {
      // 昨天夜班开始 到 当天白班开始
      console.log("昨天夜班开始 到 当天白班开始");
      if (ck_t >= night_s_ck_t_p && ck_t <= day_s_ck_t) {
        // 定时打开下班次弹框
        let delta = day_s_ck_t - now;
        let timeout = setTimeout(function () {
          openEACkDialog();
          clearTimeout(timeout);
        }, delta);
      } else {
        // 直接打开弹框
        openEACkDialog();
      }
    } else if (now >= day_s_ck_t && now <= night_s_ck_t) {
      // 当天白班开始 到 当天夜班开始
      console.log("今天白班开始 到 今天夜班开始");
      if (ck_t >= day_s_ck_t && ck_t <= night_s_ck_t) {
        // 定时打开下班次弹框
        let delta = night_s_ck_t - now;
        let timeout = setTimeout(function () {
          openEACkDialog();
          clearTimeout(timeout);
        }, delta);
      } else {
        // 直接打开弹框
        openEACkDialog();
      }
    } else if (now >= night_s_ck_t && now <= day_s_ck_t_n) {
      // 当天夜班开始 到 明天白班开始
      console.log("今天夜班开始 到 明天白班开始");
      if (ck_t >= night_s_ck_t && ck_t <= day_s_ck_t_n) {
        // 定时打开下班次弹框
        let delta = day_s_ck_t_n - now;
        let timeout = setTimeout(function () {
          openEACkDialog();
          clearTimeout(timeout);
        }, delta);
      } else {
        // 直接打开弹框
        openEACkDialog();
      }
    }

  } else {
    // 直接打开弹框
    openEACkDialog();
  }


}

/**
 * 双击事件
 * @param {*} EA 
 * @param {*} res 
 */
function doOnDblClick(EA, res, index) {
  if (globalData.clickFlag) {
    // 取消上次延时未执行的方法
    globalData.clickFlag = clearTimeout(globalData.clickFlag);

  }

  /**双击事件处理 */
  console.log("双击", EA, res, index);
  let item = globalData.data[index];
  // 判断能不能取消
  // if (item.sel === SELECT_STATE.NONE) {
  if (item.sel.length === 0) {
    return;
  } else {

    let i1 = item.sel.indexOf(SELECT_STATE.J1);
    if (i1 != -1) {
      item.sel.splice(i1, 1);
      globalData.J1_sel = false;


      document.getElementById("J1_EA").value = "";
      document.getElementById("J1_act").value = "";
      document.getElementById("J1_res").value = "";

      document.getElementById('num-' + index).classList.remove("selected");
      document.getElementById('order-' + index + '-1').classList.remove("selected");

    }

    let i2 = item.sel.indexOf(SELECT_STATE.J2);
    if (i2 != -1) {
      item.sel.splice(i2, 1);

      document.getElementById("J2_EA").value = "";
      document.getElementById("J2_act").value = "";
      document.getElementById("J2_res").value = "";

      document.getElementById('num-' + index).classList.remove("selected");

      document.getElementById('order-' + index + '-2').classList.remove("selected");
      globalData.J2_sel = false;

    }

    let i3 = item.sel.indexOf(SELECT_STATE.J3);
    if (i3 != -1) {
      item.sel.splice(i3, 1);

      document.getElementById("J3_EA").value = "";
      document.getElementById("J3_act").value = "";
      document.getElementById("J3_res").value = "";

      document.getElementById('num-' + index).classList.remove("selected");

      document.getElementById('order-' + index + '-3').classList.remove("selected");
      globalData.J3_sel = false;

    }

    let i4 = item.sel.indexOf(SELECT_STATE.J4);
    if (i4 != -1) {
      item.sel.splice(i4, 1);

      document.getElementById("J4_EA").value = "";
      document.getElementById("J4_act").value = "";
      document.getElementById("J4_res").value = "";

      document.getElementById('num-' + index).classList.remove("selected");

      document.getElementById('order-' + index + '-4').classList.remove("selected");
      globalData.J4_sel = false;

    }

    calc();
  }
}

function onClearingClick() {
  document.getElementById("J1_EA").value = "";
  document.getElementById("J1_act").value = "";
  document.getElementById("J1_res").value = "";

  document.getElementById("J2_EA").value = "";
  document.getElementById("J2_act").value = "";
  document.getElementById("J2_res").value = "";

  document.getElementById("J3_EA").value = "";
  document.getElementById("J3_act").value = "";
  document.getElementById("J3_res").value = "";

  document.getElementById("J4_EA").value = "";
  document.getElementById("J4_act").value = "";
  document.getElementById("J4_res").value = "";

  document.getElementById("pjcc").value = "";
  document.getElementById("cc").value = "";
  document.getElementById("bl").value = "";

  document.getElementById("pjgs").value = "";

  globalData.data.forEach(function (el, index) {
    if (el.sel.length > 0) {
      document.getElementById('num-' + index).classList.remove("selected");

      document.getElementById('order-' + index + '-1').classList.remove("selected");
      document.getElementById('order-' + index + '-2').classList.remove("selected");
      document.getElementById('order-' + index + '-3').classList.remove("selected");
      document.getElementById('order-' + index + '-4').classList.remove("selected");
      el.sel = [];
    }
  });

  globalData.J1_sel = false;
  globalData.J2_sel = false;
  globalData.J3_sel = false;
  globalData.J4_sel = false;

}

/**
 * 
 */
function createAllEANumsByEA() {
  const EA = globalData.appData.EA;
  // console.log(new Decimal(min_tr).div(new Decimal(EA)).floor().toString(), new Decimal(max_tr).div(new Decimal(EA)).ceil().toString());

  /*
  // 最小投入值
  const min_tr = 300;
  // 最大投入值
  const max_tr = 3000;

  let min_ea = new Decimal(41);

  let val_t = new Decimal(min_tr).div(new Decimal(EA)).floor().sub(10);
  min_ea = min_ea > val_t ? min_ea : val_t;

  let max_ea = new Decimal(220);

  val_t = new Decimal(max_tr).div(new Decimal(EA)).ceil().add(10);
  max_ea = max_ea > val_t ? max_ea : val_t;

  // console.log(min_ea.toString(), max_ea.toString());
  console.log(min_ea.toNumber(), max_ea.toNumber());
  */



  globalData.data = [];


  /**生成所有num */
  let nums_Root_O = document.getElementById("nums-container");
  let o = "";
  for (let i = globalData.appData.EA_min, index = 0; i <= globalData.appData.EA_max; i++, index++) {
    // 四舍五入小数点后零位（及整数）
    let val_act = new Decimal(EA).mul(i);

    // let val = val_act.toDecimalPlaces(0, Decimal.ROUND_HALF_UP).toNumber();
    // 只保留小数点后两位，三位及以上 '毫'位进一
    // let val = Math.ceil(val_act.toNumber() * 100) / 100;
    let val = val_act.toDecimalPlaces(2, Decimal.ROUND_UP).toNumber();

    o = o + '<div id="num-' + index + '" class="nums" onclick="doOnClick(' + i + ',' + val + ',' + index + ')" ondblclick="doOnDblClick(' + i + ',' + val + ',' + index + ')">\n<div><span style="font-size: 16px;color:green;">' + i + '</span><span style="color: rgba(242, 79, 3, 1); font-size: 12px; margin-left: 5px;">EA</span></div>\n<div><span style="color: #b8029d; font-size: 14px; font-weight: 400;">' + val + '</span></div>\n<div class="order lt" id="order-' + index + '-1">1</div>\n<div class="order rt" id="order-' + index + '-2">2</div>\n<div class="order lb" id="order-' + index + '-3">3</div>\n<div class="order tb" id="order-' + index + '-4">4</div>\n</div>';

    globalData.data.push({
      i: index,
      EA: i,
      res: val,
      act: val_act.toNumber(),
      sel: []
    });


  }

  nums_Root_O.innerHTML += o;
}

/**
 * 
 */
function refreshAllNums() {
  let nums_Root_O = document.getElementById("nums-container");
  nums_Root_O.innerHTML = '';
  createAllEANumsByEA();

  globalData.J1_sel = false;
  globalData.J2_sel = false;
  globalData.J3_sel = false;
  globalData.J4_sel = false;

  document.getElementById("J1_EA").value = "";
  document.getElementById("J1_act").value = "";
  document.getElementById("J1_res").value = "";


  document.getElementById("J2_EA").value = "";
  document.getElementById("J2_act").value = "";
  document.getElementById("J2_res").value = "";

  document.getElementById("J3_EA").value = "";
  document.getElementById("J3_act").value = "";
  document.getElementById("J3_res").value = "";

  document.getElementById("J4_EA").value = "";
  document.getElementById("J4_act").value = "";
  document.getElementById("J4_res").value = "";

  document.getElementById("pjcc").value = "";
  document.getElementById("cc").value = "";
  document.getElementById("bl").value = "";
  document.getElementById("pjgs").value = "";


  let o_ea_show = document.getElementById("ea_show");
  o_ea_show.innerText = globalData.appData.EA;

  document.getElementById("ea_show_ck").innerText = globalData.appData.EA;
}


function calc() {
  // 计算平均产出
  // let pjgs_str = "(1245+1234+1377+1235) / 2"; 
  if (!globalData.J1_sel && !globalData.J2_sel && !globalData.J3_sel && !globalData.J4_sel) {
    document.getElementById("pjcc").value = "";
    document.getElementById("pjgs").value = "";
    document.getElementById("cc").value = "";
    document.getElementById("bl").value = "";
  } else {
    let a = 0;
    let b = 0;
    let c = 0;
    let d = 0;
    let J_arr = [];
    if (globalData.J1_sel) {
      a = document.getElementById("J1_res").value;
      J_arr.push(a);
    }
    if (globalData.J2_sel) {
      b = document.getElementById("J2_res").value;
      J_arr.push(b);
    }
    if (globalData.J3_sel) {
      c = document.getElementById("J3_res").value;
      J_arr.push(c);
    }
    if (globalData.J4_sel) {
      d = document.getElementById("J4_res").value;
      J_arr.push(d);
    }
    let res = new Decimal(a).add(b).add(c).add(d);

    let pjgs_str = "";
    let pjcc;
    // console.log(J_arr);
    if (J_arr.length === 1) {
      pjgs_str = J_arr[0] + "";
      res = res.toNumber();

      pjcc = res;
    } else {
      pjgs_str = "( ";
      pjgs_str += (J_arr.join(" + "));
      // console.log(J_arr.join(" + "))
      pjgs_str += " ) / 2 ";

      // res = res.div(2).toNumber();
      res = res.div(2);
      // console.log(res);

      // 浮点数计算误差 2076.51 * 100 = 207651.00000000003
      // pjcc = Math.ceil(res * 100) / 100;

      // new Decimal(EA)
      /**
       * Decimal.ROUND_UP 向远离零的方向舍入
       * 如果数字是正数吗，则向上舍入；如果是负数，则向下舍入。即绝对值增大
       * Decimal.ROUND_CEIL 向正无穷方向舍入
       * 无论数字是正数还是负数，总是向上舍入到最近的整数或指定的小数位数。
       * Decimal.ROUND_HALF_UP 四舍五入
       * 
       * Decimal.ROUND_HALF_EVEN 四舍六入五成双（银行家舍入法）
       */


      pjcc = res.toDecimalPlaces(2, Decimal.ROUND_UP).toNumber();


      // let tests = [1.000,1.001,1.220,2.0];
      // tests.forEach(el =>{
      //   console.log(el, new Decimal(el).toDecimalPlaces(2, Decimal.ROUND_UP).toNumber());
      // });

      console.log(pjcc);
    }

    // 要求保留小数点后两位，两位以上自动进位
    // const pjcc = Math.ceil(res * 100) / 100;
    // console.log(res, res_);
    document.getElementById("pjcc").value = pjcc;
    document.getElementById("pjgs").value = pjgs_str;

    document.getElementById("cc").value = pjcc;



    // 不良计算
    const trs = document.getElementById("trs").value;
    if (trs !== "") {
      var bl = new Decimal(trs).sub(pjcc).toNumber();

      document.getElementById("bl").value = bl;
    }
  }

}

function eaConfirmOnClickHandler() {
  let now = Date.now();
  // 当天白班开始前时间
  let day_s_ck_t = new Date(((new Date()).getYear() + 1900) + '/' + ((new Date()).getMonth() + 1) + '/' + (new Date()).getDate() + ' ' + DAY_SHIFT_EA_CK_TIME);
  // 明天白班开始前时间
  let day_s_ck_t_n = day_s_ck_t.getTime() + 86400000;
  day_s_ck_t = day_s_ck_t.getTime();
  // 当天夜班开始前时间
  let night_s_ck_t = new Date(((new Date()).getYear() + 1900) + '/' + ((new Date()).getMonth() + 1) + '/' + (new Date()).getDate() + ' ' + NIGHT_SHIFT_EA_CK_TIME);
  // 昨天夜班开始前时间
  let night_s_ck_t_p = night_s_ck_t.getTime() - 86400000;
  night_s_ck_t = night_s_ck_t.getTime();

  // console.log(night_s_ck_t_p, day_s_ck_t, night_s_ck_t, day_s_ck_t_n);

  if (now >= night_s_ck_t_p && now <= day_s_ck_t) {
    // 昨天夜班开始 到 当天白班开始
    console.log("昨天夜班开始 到 当天白班开始");
    // 定时打开下班次弹框
    let delta = day_s_ck_t - now;
    let timeout = setTimeout(function () {
      openEACkDialog();
      clearTimeout(timeout);
    }, delta);

  } else if (now >= day_s_ck_t && now <= night_s_ck_t) {

    // 当天白班开始 到 当天夜班开始
    console.log("今天白班开始 到 今天夜班开始");
    // 定时打开下班次弹框
    let delta = night_s_ck_t - now;
    let timeout = setTimeout(function () {
      openEACkDialog();
      clearTimeout(timeout);
    }, delta);

  } else if (now >= night_s_ck_t && now <= day_s_ck_t_n) {
    // 当天夜班开始 到 明天白班开始
    console.log("今天夜班开始 到 明天白班开始");

    // 定时打开下班次弹框
    let delta = day_s_ck_t_n - now;
    let timeout = setTimeout(function () {
      openEACkDialog();
      clearTimeout(timeout);
    }, delta);

  }


  globalData.appData.ck_EA_t = now;
  setCookie(DATA_KEY, JSON.stringify(globalData.appData), 36500);


  document.getElementById("OAL-check-dialog").style.display = "none";
}

function goSetEAOnClickHandler() {
  // document.getElementById("OAL-check-dialog").style.display = "none";
  eaConfirmOnClickHandler(); // 修改也相当于 确认值不对，确认了
  openSettingDialog();
}

function openEACkDialog() {
  document.getElementById("OAL-check-dialog").style.display = "block";
}




function dialogMaskOnClick() {
  document.getElementById("setting-dialog").style.display = "none";
}

function openSettingDialog() {
  document.getElementById("setting-dialog").style.display = "block";
}

function addEAOnClick() {
  /*** 校验 */


  let reg_number = /^(0|([1-9]\d*))(\.[0-9]{1,6})?$/;
  let o_addEA = document.getElementById("add_EA");
  let o_tip_info = document.getElementById("tip_info");
  if (!reg_number.test(o_addEA.value)) {
    o_tip_info.innerText = "输入错误";
    return;
  }


  let res = globalData.appData.EA_list.some(function (el) {
    return el === parseFloat(o_addEA.value)
  });
  if (res) {
    o_tip_info.innerText = "该总长值已存在";
    return;
  }

  o_tip_info.innerText = "";




  try {
    let value = parseFloat(o_addEA.value);
    globalData.appData.EA_list.push(value);
    // localStorage.setItem(DATA_KEY, JSON.stringify(globalData.appData));
    setCookie(DATA_KEY, JSON.stringify(globalData.appData), 36500);

    let o_EA_list = document.getElementById("EA_list");

    /*
    let o_new = document.createElement("div");
    o_new.classList.add("EA", "mybtn");
    o_new.id = "set-EA-" + value;
    // o_new.innerText = o_addEA.value;
    o_new.innerHTML = ("\n<span>"+o_addEA.value+'</span>\n<div class="del_btn" onclick="delEADoOnDblClick(event,'+value+')">×</div>');
    o_new.onclick = function () { setEADoOnClick(value);};
    // o_new.ondblclick = function () { delEADoOnDblClick(value) };
    // o_EA_list.append(o_new);
    // o_EA_list.innerHTML = o_EA_list.innerHTML + o_new;
    */

    // let o_new_str = '<div class="EA mybtn" ondblclick="setEADoOnDblClick(' + value + ')" onclick="setEADoOnClick(' + value + ')" id="set-EA-' + value + '">' + o_addEA.value + "</div>";
    let o_new_str = '<div class="EA mybtn"  onclick="setEADoOnClick(' + value + ')" id="set-EA-' + value + '">' + '\n<span>' + value + '</span>\n<div class="del_btn" onclick="delEADoOnDblClick(event,' + value + ')">×</div>\n</div>';
    o_EA_list.innerHTML += o_new_str;

    /**
    let o_ea_sel = document.getElementById("ea_sel");
    let newOption = document.createElement("option");
    newOption.id = "sel-opt-" + o_addEA.value;
    newOption.text = o_addEA.value + "";
    newOption.value = o_addEA.value;

    o_ea_sel.add(newOption);
     */



    // o_tip_info.innerText = "添加成功";

    // 修改当前总长值为刚添加的值
    {
      document.getElementById("set-EA-" + globalData.appData.EA).classList.remove("selected");
      globalData.appData.EA = value;
      document.getElementById("set-EA-" + value).classList.add("selected");
      globalData.appData.set_EA_t = Date.now();
      setEATipShow();

      // localStorage.setItem(DATA_KEY, JSON.stringify(globalData.appData));
      setCookie(DATA_KEY, JSON.stringify(globalData.appData), 36500);
      refreshAllNums();
    }

    o_tip_info.innerText = "添加并修改总长值成功"

    o_addEA.value = "";
  } catch (error) {
    o_tip_info.innerText = "添加失败";
  }
}

/**
 * 修改保存EA_min ; EA_max
 */
function optEAOnClick() {
  /*** 校验 */
  let reg_number = /^[1-9]\d*$/;
  let o_EA_min = document.getElementById("EA_min");
  let o_EA_max = document.getElementById("EA_max");
  let o_tip_info = document.getElementById("tip_info");
  if (!reg_number.test(o_EA_min.value)) {
    o_tip_info.innerText = "最小EA数输入错误";
    return;
  }

  if (!reg_number.test(o_EA_max.value)) {
    o_tip_info.innerText = "最大EA数输入错误";
    return;
  }

  if (parseInt(o_EA_max.value) <= parseInt(o_EA_min.value)) {
    o_tip_info.innerText = "最大EA数必须大于最小EA数";
    return;
  }

  o_tip_info.innerText = "";

  try {
    globalData.appData.EA_min = parseInt(o_EA_min.value);
    globalData.appData.EA_max = parseInt(o_EA_max.value);
    // localStorage.setItem(DATA_KEY, JSON.stringify(globalData.appData));
    setCookie(DATA_KEY, JSON.stringify(globalData.appData), 36500);
    refreshAllNums();
    o_tip_info.innerText = "修改成功";
  } catch (error) {
    o_tip_info.innerText = "修改失败";
  }
}

/**
 * EA设置菜单EA单击事件
 * @param {number} EA
 */
function setEADoOnClick(EA) {
  // xxxx

  /**只考虑一次只能点一个地方 */
  const wait = 200;
  if (globalData.clickFlag1) {
    // 取消上次延时未执行的方法
    globalData.clickFlag1 = clearTimeout(globalData.clickFlag1);

  }
  globalData.clickFlag1 = setTimeout(function () {
    /**单击事件处理 */
    console.log("单击", EA);
    if (EA !== globalData.appData.EA) {
      document.getElementById("set-EA-" + globalData.appData.EA).classList.remove("selected");
      globalData.appData.EA = EA;
      document.getElementById("set-EA-" + EA).classList.add("selected");
      globalData.appData.set_EA_t = Date.now();
      setEATipShow();

      // localStorage.setItem(DATA_KEY, JSON.stringify(globalData.appData));
      setCookie(DATA_KEY, JSON.stringify(globalData.appData), 36500);
      refreshAllNums();
      let o_tip_info = document.getElementById("tip_info");
      o_tip_info.innerText = "修改总长值成功";
    }


  }, wait);
}

/**
 * EA设置菜单EA双击事件
 * @param {number} EA
 */
function delEADoOnDblClick(e, EA) {
  const evt = e || window.event;
  evt.stopPropagation();
  if (globalData.clickFlag1) {
    // 取消上次延时未执行的方法
    globalData.clickFlag1 = clearTimeout(globalData.clickFlag1);

  }

  /**双击事件处理 */
  console.log("双击", EA);

  let o_tip_info = document.getElementById("tip_info");
  if (globalData.appData.EA_list.length <= 1) {
    // 不能删除最后一个
    o_tip_info.innerText = "不能删除最后一个";
    return false;
  }
  const id = "set-EA-" + EA;
  let o_EA_list = document.getElementById("EA_list");
  // document.getElementById(id).remove();
  o_EA_list.removeChild(document.getElementById(id));
  let arr = globalData.appData.EA_list;
  for (let index = 0; index < arr.length; index++) {
    const ele = arr[index];
    if (ele === EA) {
      globalData.appData.EA_list.splice(index, 1);
      break;
    }
  }
  // localStorage.setItem(DATA_KEY, JSON.stringify(globalData.appData));
  setCookie(DATA_KEY, JSON.stringify(globalData.appData), 36500);

  // document.getElementById("sel-opt-" + EA).remove();
  o_tip_info.innerText = "删除成功";


  // 如果删除的是正在使用的
  if (globalData.appData.EA === EA) {
    globalData.appData.EA = globalData.appData.EA_list[0];
    // localStorage.setItem(DATA_KEY, JSON.stringify(globalData.appData));
    setCookie(DATA_KEY, JSON.stringify(globalData.appData), 36500);

    document.getElementById("set-EA-" + globalData.appData.EA).classList.add("selected");

    o_tip_info.innerText = "删除成功;当前总长值修改为" + globalData.appData.EA;
    globalData.appData.set_EA_t = Date.now();
    setEATipShow();

    /**重新计算；刷新input */
    refreshAllNums();
  }

  return false;


}

function openNumKeyboard() {
  // console.log("openNumKeyboard...");
  var o_nkb = document.getElementById("num-keyboard-dialog");
  o_nkb.style.display = "block";
  var o_ipt = document.getElementById("num-ipt");
  o_ipt.value = document.getElementById("trs").value;
  document.getElementById("scz").value = globalData.keyboard.lastVal;
  onbdInput();
  // 自动获取焦点
  o_ipt.focus();

}

function fastSetupVal() {
  if (globalData.keyboard.lastVal !== "") {
    var o_ipt = document.getElementById("num-ipt");
    o_ipt.value = globalData.keyboard.lastVal;
    onbdInput();
    // 自动获取焦点
    o_ipt.focus();
  }
}

function autoFocus() {
  var o_nkb = document.getElementById("num-keyboard-dialog");
  if (o_nkb && o_nkb.style.display == "block") {
    var o_ipt = document.getElementById("num-ipt");
    // 自动获取焦点
    o_ipt && o_ipt.focus();
    // console.log("autoFocus...");
  }
}

function closeNumKeyboard() {
  var o_nkb = document.getElementById("num-keyboard-dialog");
  o_nkb.style.display = "none";
}

function onKeyAreaClick(event) {
  const ev = event || window.event;
  const target = ev.target || ev.srcElement;
  // console.log("target:", target,target.id);
  if (target && target.id && target.dataset.key !== undefined) {
    onPressKey(target.dataset.key);
  }
}

function onPressKey(key) {
  var o_ipt = document.getElementById("num-ipt");
  // 自动获取焦点
  o_ipt && o_ipt.focus();
  switch (key) {
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '.':
    case '-':
      o_ipt.value = o_ipt.value + key;
      o_ipt.oninput();
      break;
    case '←':
      o_ipt.value = o_ipt.value.substring(0, o_ipt.value.length - 1);
      o_ipt.oninput();
      break;
    case 'X':
      o_ipt.blur();
      closeNumKeyboard();
      break;

    case 'Enter':
      if (globalData.keyboard.iptCheckRes) {
        globalData.keyboard.lastVal = o_ipt.value;
        document.getElementById("trs").value = o_ipt.value;
        const pjcc = document.getElementById("pjcc").value;
        if (pjcc !== "") {
          var bl = new Decimal(o_ipt.value).sub(pjcc).toNumber();
          document.getElementById("bl").value = bl;
        } else {
          document.getElementById("bl").value = "";

        }
        o_ipt.blur();
        closeNumKeyboard();

      }

      break;

    default:
      break;
  }
}

function onIptClrClick() {
  var o_ipt = document.getElementById("num-ipt");
  o_ipt.value = "";
  o_ipt.oninput();
  o_ipt.focus();
}

function onbdInput() {
  var o_ipt = document.getElementById("num-ipt");
  const val = o_ipt.value;
  // console.log("value change...");

  var rv = boardInputCheck(val);
  globalData.keyboard.iptCheckRes = rv.res;

  var o_tip = document.getElementById("bd-ipt-err-tip");
  if (!rv.res) {
    if (o_tip) {
      o_tip.style.display = "block";
      o_tip.innerText = rv.error;
    }
  } else {
    o_tip.style.display = "none";
    o_tip.innerText = "";
  }

}

function boardInputCheck(val) {
  var res = true;
  var error = "";

  if (val.length === 0 || val.trim().length === 0) {
    error = "输入为空";
    return {
      res: false,
      error: error
    };
  }


  const num_r = /^(\-?(0|([1-9]\d*)))(\.\d+)?$/;
  res = num_r.test(val);
  if (!res) {
    error = "输入有误";
    return {
      res: res,
      error: error
    };
  }


  // range test
  const min = 0;
  const max = 5000;
  if (val < min || val > max) {
    error = "输入有误";
    return {
      res: false,
      error: error
    };
  }




  return {
    res: true,
    error: ""
  };

}


/**
 * 节流（Throttle）
 * @function 
 * @description 节流的作用是限制函数在一定时间内只能执行一次。即使用户频繁点击按钮，函数也只会在设定的时间间隔内执行一次。节流适用于需要控制频繁触发的场景，如滚动事件、窗口调整大小事件等。
 * @param func 
 * @param wait 
 * @returns 
 * @example
 * // 节流适用于需要在固定时间间隔内执行的场景，如滚动事件、窗口调整大小事件等。
 * const button = document.getElementById('submit');
 * button.addEventListener('click', throttle(function(){
 *      console.log('按钮点击');
 * }, 1000));
 */
function throttle(func, wait) {
  let timeout;
  return function () {
    let context = this;
    let args = arguments;
    if (!timeout) {
      timeout = setTimeout(function () {
        timeout = null;
        func.apply(context, args);
      }, wait);
    }
  };
}
/**
 * 防抖（Debounce）
 * @function 
 * @description 防抖的作用是将多次触发的事件合并为一次，即在事件触发后的一段时间内，如果没有再次触发事件，才会执行函数。防抖适用于需要减少频繁触发的场景，如搜索框输入、窗口滚动结束等。
 * @param func 
 * @param {number} [wait = 500] 默认值500ms
 * @returns 
 * @example
 * // 节流适用于需要在固定时间间隔内执行的场景，如滚动事件、窗口调整大小事件等。
 * // 对于防止按钮重复点击，节流更为合适，因为它可以确保在设定的时间间隔内，按钮点击事件只会触发一次，从而避免了多次提交的问题
 * const button = document.getElementById('submit');
 * button.addEventListener('click', debounce(function(){
 *      console.log('按钮点击');
 * }, 1000))
 */
function debounce(func, wait) {
  let timeout;
  return function () {
    let context = this;
    let args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      func.apply(context, args);
    }, wait);
  };
}

function setCookie(name, value, expires) {
  var date = new Date();
  date.setTime(date.getTime() + (expires * 24 * 60 * 60 * 1000));
  var expires = "; expires=" + date.toUTCString();
  document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(name) {
  let cookieArr = document.cookie.split(";");
  let flag = false;
  for (let i = 0; i < cookieArr.length; i++) {
    let cookiePair = cookieArr[i].split('=');
    // console.log("cookiePair[1] ",cookiePair[1]);
    // console.log("xxx",decodeURIComponent(cookiePair));
    if (name === cookiePair[0].trim()) {
      flag = true;
      // return decodeURIComponent(cookiePair);
      return cookiePair[1];
    }
  }
  if (!flag) {
    return null;
  }

}